import { getUserCode, goLogin, registerUser, getUserInfo, userLogOut } from "@/api/user/index.js";
import { setToken, getToken, removeToken } from "@/utils/settoken";
const state = {
  code: "",
  token: getToken(),
  nickName: "",
};
const mutations = {
  GETCODE(state, code) {
    state.code = code;
  },
  TOKEN(state, token) {
    state.token = token;
    // localStorage.setItem("TOKEN", token);
  },
  LOGOUT(state) {
    removeToken();
    state.token = "";
  },
  USERNAME(state, nickName) {
    state.nickName = nickName;
  },
};
const actions = {
  //验证码
  async getCode({ state, commit, dispatch }, phone) {
    let result = await getUserCode(phone);
    console.log(result);
    if (result.code == 200) {
      commit("GETCODE", result.data);
      return "";
    } else {
      return Promise.reject();
    }
  },
  //用户注册
  async userRegister({ state, commit, dispatch }, data) {
    console.log(data);
    let result = await registerUser(data);
    if (result.code == 200) {
      return "";
    } else {
      return Promise.reject(result.message);
    }
  },
  //用户登录
  async userLogin({ state, commit, dispatch }, data) {
    let result = await goLogin(data);
    if (result.code == 200) {
      commit("TOKEN", result.data.token);
      setToken(result.data.token);
      return "";
    } else {
      return Promise.reject();
    }
  },
  //获取用户信息
  async userInfo({ state, commit, dispatch }) {
    let result = await getUserInfo();
    if (result.code == 200) {
      commit("USERNAME", result.data.nickName);
      return "";
    } else {
      return Promise.reject();
    }
  },
  //用户退出登陆
  async logout({ state, commit, dispatch }) {
    let result = await userLogOut();
    if (result.code == 200) {
      commit("LOGOUT");
      return "";
    } else {
      return Promise.reject();
    }
  },
};
const getters = {};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
